package com.liuwei.spring.cloud.framework.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Description : 
 * @Author Evan Liu
 * @Date 2018年10月15日
 */
@Data
public class Pager {

	@Schema(description="默认开启分页",example="true",required=false)
	private boolean openPager = true;

	@Schema(description="当前页",example="1",required=false)
	private int current = 1;

	@Schema(description="当前页大小",example="10",required=false)
	private int size = 10;

	@Schema(description="最大行数限制",example="10000",required=false)
	private static final int maxLimit = 10000;
	
	@Schema(description="排序字段",example="id",required=false)
	private String orderBy;
	
	@Schema(description="是否正序,默认true",example="true",required=false)
	private Boolean asc;

	/**
	 * 默认最大分页大小 = 10000
	 * @return
	 */
	public int getSize() {
		//分页大小限制防止攻击
		if(openPager){
			if(size<0 || size > maxLimit) {
				throw new RuntimeException("Page size parameter illegal");
			}
		}
		return size;
	}

	/**
	 * orderby 防止 SQL 注入
	 * @return
	 */
	public String getOrderBy() {
		if(!StringUtils.isEmpty(this.orderBy)) {
			String oldOrderby = this.orderBy;
			String newOrderby = Pager.filterString(orderBy);
			if(StringUtils.equals(oldOrderby, newOrderby)) {
				return Pager.filterString(orderBy);
			}else {
				throw new RuntimeException("OrderBy parameter illegal");
			}
		}
		return this.orderBy;
	}

	/**
	 * 过滤 SQL 特殊字符
	 * https://www.cnblogs.com/interdrp/p/5586587.html
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static String filterString(String str) throws PatternSyntaxException {
		// 只允许字母和数字 // String regEx ="[^a-zA-Z0-9]"; 
		// 清除掉所有特殊字符 
		//String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		//保留.
		String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\]_<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx); 
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}
	
}


